import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/layout'
import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'

import store from '@/store'

const Login = () => import('@/views/login')
const Search = () => import('@/views/search')
const Myorder = () => import('@/views/myorder')
const Pay = () => import('@/views/pay')
const ProDetail = () => import('@/views/prodetail')
const SearchList = () => import('@/views/search/list')

Vue.use(VueRouter)

// const routes = []
const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        { path: '/home', component: Home },
        { path: '/category', component: Category },
        { path: '/cart', component: Cart },
        { path: '/user', component: User }
      ]
    },
    { path: '/myorder', component: Myorder },
    { path: '/pay', component: Pay },
    // 动态路由传参，确定是那个商品
    { path: '/prodetail/:id', component: ProDetail },
    { path: '/search', component: Search },
    { path: '/searchlist', component: SearchList }
  ]
})

// 全局前置导航守卫(所有路由跳转之前都会执行，只有放行了才会跳转，对于支付页面，订单页面是不能放行的)
// 1. to 往哪里去， 到哪去的路由信息对象（路径，参数）
// 2. from 从哪里来， 从哪来的路由信息对象（路径，参数）
// 3. next() 是否放行
// 如果next()调用，就是放行，放行到to的路径
// next(路径) 拦截到某个路径页面
const authUrls = ['/pay', '/myorder'] // 这个路由访问直接要登陆才能访问
router.beforeEach((to, from, next) => {
  // console.log(to, from, next)
  // 判断to.path是否在数组authUrls中
  if (!authUrls.includes(to.path)) {
    // 非权限页面，直接放行
    next()
    return
  }

  // 是权限页面,判断token
  /*
    const token = store.state.user.userInfo.token 太长就在store的全局模块getters中定义一个方法
    为什么是store.state 因为模块user相当于store的数据，state是store这个模块的数据
  */
  const token = store.getters.token // 这个store是store模块的方法
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
